package com.jwiki.app.jkeeper.service.impl;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jwiki.app.jkeeper.common.jdbc.JdbcUtils;
import com.jwiki.app.jkeeper.common.jdbc.Page;
import com.jwiki.app.jkeeper.config.Configurations;
import com.jwiki.app.jkeeper.controller.form.PropertyForm;
import com.jwiki.app.jkeeper.repository.bean.PropertyBean;
import com.jwiki.app.jkeeper.repository.mapper.PropertyMapper;
import com.jwiki.app.jkeeper.repository.model.PropertyModel;
import com.jwiki.app.jkeeper.service.PropertyService;

@Service
public class PropertyServiceImpl implements PropertyService {

    @Autowired
    private PropertyMapper propertyMapper;

    @Override
    public List<PropertyModel> getProperty(PropertyForm form) {
        if (form.getId() == null) {
            PropertyModel model = new PropertyModel();
            BeanUtils.copyProperties(form, model);
            return propertyMapper.selectList(model);
        } else {
            return Arrays.asList(propertyMapper.select(form.getId()));
        }
    }

    @Override
    public Page<PropertyBean> getPropertyByPage(PropertyForm form) {
        Page<PropertyBean> page = JdbcUtils.build().orderBy(form.getOrderBy())
                .limit(form.getOffset(), form.getLimit()).getPage();
        PropertyBean bean = new PropertyBean();
        BeanUtils.copyProperties(form, bean);
        page.setData(propertyMapper.selectProperty(bean));
        return page;
    }

    @Override
    public boolean saveProperty(PropertyForm form) {
        PropertyModel model = new PropertyModel();
        BeanUtils.copyProperties(form, model);
        model.setUpdateBy(form.getUserName());

        if (model.getId() == null) {
            model.setCreateBy(form.getUserName());
            return propertyMapper.insert(model) > 0;
        } else {
            if (StringUtils.isNotBlank(form.getImageUrl())) {
                deleteImageFile(Arrays.asList(model.getId())); 
            }
            return propertyMapper.update(model) > 0;
        }
    }

    @Override
    public boolean removeProperty(List<Long> propertyIds) {
        deleteImageFile(propertyIds);
        return propertyMapper.deleteList(propertyIds) > 0;
    }

    protected void deleteImageFile(List<Long> propertyIds) {
        String baseUrl = Configurations.getResourceBase();
        propertyIds.forEach(propertyId -> {
            PropertyModel model = propertyMapper.select(propertyId);
            if (StringUtils.isNotBlank(model.getImageUrl())) {
                FileUtils.deleteQuietly(new File(baseUrl, model.getImageUrl()));
            }
        });
    }

}
